//
//  AppDelegate.m
//  quanminzhekou
//
//  Created by zxl on 15/1/4.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "AppDelegate.h"
#import "VersionViewModel.h"
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"
#import "UMSocialWechatHandler.h"
#import "GexinSdk.h"
#import "UMFeedback.h"
#import "UMOpus.h"

@interface AppDelegate () <UIAlertViewDelegate, GexinSdkDelegate>
@property (nonatomic) NSString* currentVersion;
@property (nonatomic) MKNetworkOperation* versionOperation;
@property (nonatomic) VersionModel* versionModel;
@property (nonatomic) GexinSdk* gexinPusher;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    _currentVersion = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
    NSString* app_version = [[NSUserDefaults standardUserDefaults] objectForKey:@"app_version"];
    
    if (![app_version isKindOfClass:[NSString class]] || 0 == app_version.length) {//应用首次使用
        [[NSUserDefaults standardUserDefaults] setObject:_currentVersion forKey:@"app_version"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Remote_Notification_OnOff"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } else if (![_currentVersion isEqualToString:app_version]) {//应用升级后首次使用
        [[NSUserDefaults standardUserDefaults] setObject:_currentVersion forKey:@"app_version"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    [self setupUmengShare];
    [self setupUmengFeedback];
//    [self checkVersion];//检查版本更新
    [self setupRemoteNotification];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupRemoteNotification) name:@"NotificationForRemote" object:nil];
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [self stopGexinPusher];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    self.gexinPusher = self.gexinPusher;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [self.gexinPusher registerDeviceToken:token];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    [self.gexinPusher registerDeviceToken:@""];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [UMSocialSnsService handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return  [UMSocialSnsService handleOpenURL:url];
}

#pragma mark - check version
- (void)checkVersion {
    _currentVersion = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
    
    NSString* path = [[CommonEngine sharedInstance] urlPathForVersion];
    _versionOperation = [[CommonEngine sharedInstance] getOperationWithURLPath:path shouldCache:NO completionHandler:^(NSDictionary *result) {
        NSNumber* status = [result objectForKey:@"status"];
        if (1 == status.integerValue) {
            NSArray* res = [result objectForKey:@"res"];
            _versionModel = [[VersionModel alloc] initWithDic:[res firstObject]];
            
            [[NSUserDefaults standardUserDefaults] setObject:_versionModel.name forKey:@"Version_Service"];
            [[NSUserDefaults standardUserDefaults] setObject:_versionModel.url forKey:@"Version_URL"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (![_versionModel.name isEqualToString:self.currentVersion]) {
//                    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"检查到新版本！" delegate:self cancelButtonTitle:@"稍后" otherButtonTitles:@"去更新", nil];
//                    [alert show];
                }
            });
        }
        
    } errorHandler:^(NSError *errMsg) {
        
    }];
}

#pragma mark - Umeng
- (void)setupUmengShare {
    [UMSocialData setAppKey:UmengAppkey];//注册友盟社会化分享
    
    //打开调试log的开关
//    [UMSocialData openLog:YES];
    
    //打开新浪微博的SSO开关
    [UMSocialSinaHandler openSSOWithRedirectURL:nil];
    
    // 设置分享到QQ空间的应用Id，和分享url 链接
    [UMSocialQQHandler setQQWithAppId:QQAppID appKey:QQAppKey url:QQURL];
    // 设置支持没有客户端情况下使用SSO授权
    [UMSocialQQHandler setSupportWebView:YES];
    
    //设置微信AppId，设置分享url，默认使用友盟的网址
    [UMSocialWechatHandler setWXAppId:WeChatAppID appSecret:WeChatAppSecret url:WeChatURL];
}

- (void)setupUmengFeedback {
    [UMFeedback setAppkey:UmengAppkey];
    [UMOpus setAudioEnable:YES];
}

#pragma mark - APNS
- (GexinSdk*)gexinPusher {
    if (nil == _gexinPusher) {
        NSString* version = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
        
        _gexinPusher = [GexinSdk createSdkWithAppId:GeTuiAppId appKey:GeTuiAppKey appSecret:GeTuiAppSecret appVersion:version delegate:self error:nil];
    }
    
    return _gexinPusher;
}

- (void)setupRemoteNotification {
    BOOL isRemoteNotificationOnOff = [[NSUserDefaults standardUserDefaults] boolForKey:@"Remote_Notification_OnOff"];
    
    if (isRemoteNotificationOnOff) {
#ifdef __IPHONE_8_0
        if (8.0 <= [UIDevice currentDevice].systemVersion.floatValue) {
            UIUserNotificationSettings* uns = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
            [[UIApplication sharedApplication] registerUserNotificationSettings:uns];
        } else {
            UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
        }
#else
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif
    } else {
        [[UIApplication sharedApplication] unregisterForRemoteNotifications];
    }
    
}

- (void)stopGexinPusher
{
    if (_gexinPusher) {
        [_gexinPusher destroy];
        _gexinPusher = nil;
    }
}

#pragma mark - GexinSdkDelegate

- (void)GexinSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推SDK已注册
    
//    NSLog(@"%s, clientId:%@", __FUNCTION__, clientId);
}

- (void)GexinSdkDidReceivePayload:(NSString *)payloadId fromApplication:(NSString *)appId
{
    // [4]: 收到个推消息
    NSData *payload = [_gexinPusher retrivePayloadById:payloadId];
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length
                                            encoding:NSUTF8StringEncoding];
        
//        NSLog(@"%s, payloadMsg:%@", __FUNCTION__, payloadMsg);
    }
}

- (void)GexinSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // [4-EXT]:发送上行消息结果反馈
//    NSString *record = [NSStrinnslogg stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
    
//    NSLog(@"%s, record:%@", __FUNCTION__, record);
}

- (void)GexinSdkDidOccurError:(NSError *)error
{
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
//    NSLog(@"%s, err:%@", __FUNCTION__, error);
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (1 == buttonIndex) {
        NSURL* url = [NSURL URLWithString:_versionModel.url];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

@end
